package cn.gson.springboot.model.service.saleservice;

import cn.gson.springboot.model.dao.cusdao.CustomerDao;
import cn.gson.springboot.model.dao.saledao.*;
import cn.gson.springboot.model.mapper.salemapper.ContractMapper;
import cn.gson.springboot.model.mapper.salemapper.CtschemeMapper;
import cn.gson.springboot.model.mapper.salemapper.OrderMapper;
import cn.gson.springboot.model.pjos.*;
import cn.gson.springboot.model.service.afterservice.MaintainService;
import cn.gson.springboot.model.vo.aftervo.MainProductVo;
import cn.gson.springboot.model.vo.salesvo.*;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.Inflater;

@Service
public class OrderService {
    @Autowired
    ContractMapper contractMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderInfoDao orderInfoDao;
    @Autowired
    OrderDetailDao orderDetailDao;
    @Autowired
    ZfhuodanDao zfhuodanDao;
    @Autowired
    DeliveryplanDao deliveryplanDao;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    CtschemeMapper ctschemeMapper;
    @Autowired
    MaintainService maintainService;
    @Autowired
    DeliverydetailsDao deliverydetailsDao;
    @Autowired
    ExchangeDao exchangeDao;


    /**
     * 订单编号
     * @return
     */
    public String selectMaxOrderName(){
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMdd");
        Date date = new Date();//获取当前时间
        String code = contractMapper.selectMaxOrdertName();
        //如果查询出来的数字为空，则为当天第一个
        if(null == code || "".equals(code)){
            code = "D"+sdf.format(date)+"-"+"1";
        }else{
            //数字不为空则加一，
            int zhi = Integer.parseInt(code)+1;
            code = "D"+sdf.format(date)+"-"+zhi+"";
        }
        return code;
    }


    public void toDayDeliveryInfo(Integer excId,Integer orderId,Integer deliverId,String exchangName,String ecName){
        //修改状态
        Exchange exchange = exchangeDao.findById(excId).get();
        exchange.setExcMainState(0);
        exchangeDao.save(exchange);

        //订单名称
        String orderName = selectMaxOrderName();

        //下单时间
        Date utilDate =new Date();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
        long time = sqlDate.getTime();
        Timestamp timestamp = new Timestamp(time);
        //最晚发货7天
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE,7);
        Date time1 = ca.getTime();
        java.sql.Date sqlEndDate = new java.sql.Date(time1.getTime());
        //由换货单转新的订单
        OrderInfo newOrderInfo = new OrderInfo();
        OrderInfo orderInfo = orderInfoDao.findById(orderId).get();
        newOrderInfo.setOrderId(0);
        newOrderInfo.setOrderState(1);
        BigDecimal bigDecimal = new BigDecimal(0.00);
        newOrderInfo.setReceivableOrder(bigDecimal);
        newOrderInfo.setOrderPayment(orderInfo.getOrderPayment());
        newOrderInfo.setBusinesId3(orderInfo.getBusinesId3());
        newOrderInfo.setQuotationId(orderInfo.getQuotationId());
        newOrderInfo.setConsigneeId(orderInfo.getConsigneeId());
        newOrderInfo.setCustomerByCustomId(orderInfo.getCustomerByCustomId());
        newOrderInfo.setOrderNoteinfo("");//备注
        newOrderInfo.setContractByContractId(orderInfo.getContractByContractId());
        newOrderInfo.setEmpId(orderInfo.getEmpId());
        newOrderInfo.setOrderTotal(bigDecimal);
        newOrderInfo.setOrderTheme(ecName+"换货订单");
        newOrderInfo.setOutboundType(orderInfo.getOutboundType());
        newOrderInfo.setCustomerName(orderInfo.getCustomerName());
        newOrderInfo.setOrderAppstate(1);
        newOrderInfo.setOrderId(0);
        newOrderInfo.setOrderName(orderName);
        newOrderInfo.setOrderTime(timestamp);
        newOrderInfo.setDeliveryTime(sqlEndDate);
        newOrderInfo.setOrderAppstate(1);
        //原订单下的产品详情
        List<Orderdetails> orderdetailsByOrderId = orderDetailDao.orderDetailInfo(orderId);
        //换货单的产品详情
        List<MainProductVo> info = maintainService.selectProductId("换货", ecName);
        //新的产品详情
        List<Orderdetails> list = new ArrayList<>();

        OrderInfo save = orderInfoDao.save(newOrderInfo);


        for(int index=0;index<orderdetailsByOrderId.size();index++){
            for(int i =0;i<info.size();i++){
                if(orderdetailsByOrderId.get(index).getDetPrid()==info.get(i).getProductSideId()){
                    orderdetailsByOrderId.get(index).setDetNum(info.get(i).getExcdNumber());
                    orderdetailsByOrderId.get(index).setOrderInfo(save);
                    list.add(orderdetailsByOrderId.get(index));
                    break;
                }
            }
        }
        orderDetailDao.saveAll(list);






    /*   Deliverydetails deliverydetails = new Deliverydetails();
       List<Deliverydetails> list = new ArrayList<>();
       Double amount=0.00;

        List<MainProductVo> info = maintainService.selectProductId("换货", ecName);
        for(MainProductVo productInfo:info){
            amount+=productInfo.getExcdNumber()*productInfo.getProductPrice();
            System.out.println("产品的编号"+productInfo.getProductSideId());
            deliverydetails.setDetaProductid(productInfo.getProductId());
            deliverydetails.setDetaPrice( productInfo.getProductPrice());
            deliverydetails.setDetaNumber(productInfo.getExcdNumber());
            deliverydetails.setDetaReturnumber(0);
            list.add(deliverydetails);
        }

        System.err.println("换货单长度"+list.size());
        //找到指定订单
        OrderInfo orderInfo = orderInfoDao.findById(orderId).get();
        //指定交付单
        Deliveryplan deliveryplan = deliveryplanDao.findById(deliverId).get();
        //指定交付详情
        List<Deliverydetails> deliverydetailsByDeliveryId = deliveryplan.getDeliverydetailsByDeliveryId();


        Date date= new Date();
        //新建 缺时间
        Deliveryplan dep = new Deliveryplan();
        dep.setDeCustomerid(deliveryplan.getDeCustomerid());
        dep.setDeContractid(deliveryplan.getDeContractid());
        dep.setDeAmount(BigDecimal.valueOf(amount));
        dep.setDePeriod(1);
        dep.setDeUserid(deliveryplan.getDeUserid());
        dep.setDeDemand(deliveryplan.getDeDemand());
        dep.setDeRemind(1);
        dep.setDeNote(deliveryplan.getDeNote());
        dep.setOrderInfoByOrderId(deliveryplan.getOrderInfoByOrderId());
        dep.setDeThere(exchangName+"换货计划");
        dep.setDeState(0);
        dep.setDeApproverid(0);
        dep.setDeAppstate(0);
        dep.setDeFhuostate(0);
        dep.setDeliverydetailsByDeliveryId(list);
        Deliveryplan save = deliveryplanDao.save(dep);

        System.err.println("交付单时间长度"+dep.getDeliverydetailsByDeliveryId().size());
        for(int i=0;i<list.size();i++){
            list.get(i).setDeliveryplan(save);
            list.get(i).setDetaReturnumber(0);
            deliverydetailsDao.save(list.get(i));
        }
        for(Deliverydetails t:list){
            System.out.println(t.toString());
        }

        System.err.println("交度list"+list.size());



*/



    }

    public List<MainProductVo>jouerFhuoInfo(Integer deliverId){
        List<MainProductVo> mainProductVos = orderMapper.jouerFhuoInfo(deliverId);
        return mainProductVos;
    }

    /**
     * 合同信息栏
     * @param orderId
     * @return
     */

    public List<OrderInfo> contractOrderInfo(Integer orderId){
        List<OrderInfo> orderInfos = orderMapper.contractOrderInfo(orderId);
        return orderInfos;
    }

    /**
     * 合同查询
     * int empid
     * @return
     */
    public List<Contract> contractsInfo(Integer empid,Integer type,String name){
       /* List<Contract> contracts = contractMapper.contractInfo(empid,type,name);*/
        List<Contract> contracts = new ArrayList<>();
        return  contracts;
    }

    /**
     * 订单查询
     * @param empId
     * @return
     */
    public List<OrderInfo> orderInfos(Integer empId,Integer type,String name){
        List<OrderInfo> orderinfo = orderMapper.orderinfo(empId,type,name);
        return orderinfo;
    }

    /**
     * 订单收货人
     * @param cusId
     * @return
     */
    public List<Receivingcontact> receInfos(Integer cusId){
        List<Receivingcontact> receivingcontacts = orderMapper.receInfo(cusId);
        return receivingcontacts;
    }

    /**
     * 新增订单
     * @param orderInfo
     */
    public void saveOrder(OrderInfo orderInfo){
        orderInfoDao.save(orderInfo);
    }

    public void saveOrderDetail(List<Orderdetails> orderdetailsList){
        orderDetailDao.saveAll(orderdetailsList);
    }

    public List<Products> productsList(Integer businesId){
        List<Products> products = orderMapper.OrderqueryDetais(businesId);
        return products;
    }


    public OrderInfo orderInfo(Integer empId,Integer id){
        OrderInfo orderdetailsinfo = orderMapper.orderdetailsinfo(empId,id);
        return orderdetailsinfo;
    }

    /**
     * 订单下的产品
     * @param orderId
     * @return
     */
    public List<Orderdetails> orderDetailDaos(Integer orderId){
        List<Orderdetails> list = orderMapper.orderProductInfo(orderId);
        return list;
    }


    /**
     * 发货单主界面
     * @return
     */
    public List<OrderInfo> orderInfos(String name,String startTime,String endTime){
        List<OrderInfo> orderInfos = orderMapper.invoiceList(name,startTime,endTime);
        return orderInfos;
    }

    /**
     * 交付管理(指定订单)
     * @param orderId
     * @return
     */
    public List<Deliverydetails> deliverydetailsList(Integer orderId){
        List<Deliverydetails> deliverydetails = orderMapper.deliverydetails(orderId);
        return deliverydetails;
    }


    /**
     * 指定订单》》指定交付计划
     * @param orderId
     * @param deliveryId
     * @return
     */
    public List<DeliveryplanVo> deliveryplanVoList(Integer orderId,Integer deliveryId){
        List<DeliveryplanVo> deliverydetails = orderMapper.deliveryProduct(orderId, deliveryId);
        return  deliverydetails;
    }


    /**
     * 收货地址
     * @param ctId
     * @return
     */
    public Receivingcontact receivList(Integer ctId){
        Receivingcontact receivingcontact = orderMapper.receivList(ctId);
        return receivingcontact;
    }


    /**
     * 保存发货单
     * @param
     */
    public void saveFhuodan(Integer customeId,String fhuodan, BigDecimal amount,
                            String kauidgs,String kauidhao,Integer shouhdz,Integer fzr,Integer orderId,Integer deliveryId){

        long time = new Date().getTime();
        java.sql.Date date = new java.sql.Date(time);
        ZfhuodanEntity zfhuodanEntity = new ZfhuodanEntity();
        Customer customer = customerDao.findById(customeId).get();
        zfhuodanEntity.setFhuoDan(fhuodan);
        zfhuodanEntity.setKauidGs(kauidgs);
        zfhuodanEntity.setKauidHao(kauidhao);
        zfhuodanEntity.setSamoUnt(amount);
        zfhuodanEntity.setCustomer(customer);
        zfhuodanEntity.setSdeliveryId(deliveryId);
        zfhuodanEntity.setsFzr(fzr);
        zfhuodanEntity.setSorderId(orderId);
        zfhuodanEntity.setShouhzId(shouhdz);
        zfhuodanEntity.setShipmentsTime(new Timestamp(new Date().getTime()));
        zfhuodanEntity.setShipmentsState(1);//发货单{无退还货记录}
        zfhuodanDao.save(zfhuodanEntity);

        /**
         * 修改交付的状态不可以再次发货
         */
        System.out.println("交付id++"+deliveryId);
        Deliveryplan deliveryplan = deliveryplanDao.findById(deliveryId).get();
        System.out.println("阿西吧"+deliveryplan.getDeThere());
        deliveryplan.setDeFhuostate(1);
        deliveryplanDao.save(deliveryplan);
    }

    public List<ZfhuodanEntity> zfhuodanList(){
        List<ZfhuodanEntity> zfhuodanEntities = orderMapper.zfhuodanList();
        return  zfhuodanEntities;
    }





    public List<OrderProductNumberVo> productNumberVoList(Integer id){

        //目标集合
        List<OrderProductNumberVo> productNumberVosList = new ArrayList<>();

        List<ProductNumberVo> productNumberVos = orderMapper.productNumberList(id);
        List<OrderProductNumberVo> orderProductNumberVos = orderMapper.orderNumberList(id);


        if(productNumberVos.size()==0){
           return orderProductNumberVos;
        }

        for(int index=0;index<productNumberVos .size();index++){
            for(int i=0;i<orderProductNumberVos.size();i++){
                if(productNumberVos.get(index).getDetaProductid()==orderProductNumberVos.get(i).getDetPrid()) {
                    if(productNumberVos.get(index).getDetaNumber()!=orderProductNumberVos.get(i).getDetNum() && productNumberVos.get(index).getDetaNumber()<orderProductNumberVos.get(i).getDetNum()){
                        OrderProductNumberVo orderProductNumberVo = new OrderProductNumberVo();
                        orderProductNumberVo.setDetPrid(productNumberVos.get(index).getDetaProductid());
                        orderProductNumberVo.setDetNum(orderProductNumberVos.get(index).getDetNum() - productNumberVos.get(index).getDetaNumber());
                        productNumberVosList.add(orderProductNumberVo);
                    }

                }
            }
        }


        return productNumberVosList;
    }

    public List<ZfhuodanEntity> zfhuodanEntityList(Integer id){
        List<ZfhuodanEntity> zfhuodanEntities = orderMapper.zfhuodanRecord(id);
        return zfhuodanEntities;

    }


    public List<Orderdetails> orderdetails(Integer orderId,Integer deliveryId){
        //目标集合
        List<Orderdetails> orderdetails=new ArrayList<>();
        //原订单产品信息
        List<Orderdetails> list = orderDetailDaos(orderId);
        //出库单下的产品
        List<Deliverydetails> list1 = ctschemeMapper.deliveryplanProductInfo(deliveryId);
        //产品id
        int [] array = new  int[list1.size()];
        //产品发货数量
        int [] productNumber=new int[list1.size()];
        //产品可退数量
        int [] returnNumber=new int[list1.size()];
        int index=0;
        for(Deliverydetails info:list1){
            Integer detPrid = info.getDetaProductid();
            Integer detaNumber = info.getDetaNumber();
            Integer detaReturnumber = info.getDetaReturnumber();
            array[index]=detPrid;
            productNumber[index]=detaNumber;
            returnNumber[index]=detaReturnumber;
            index+=1;
        }

        for(int listIndex=0;listIndex<list.size();listIndex++){
            for(int i=0;i<array.length;i++){
                if(list.get(listIndex).getDetPrid()==array[i]){
                    list.get(listIndex).setExchangeState(productNumber[i]);//代替发货数量
                    list.get(listIndex).setReturnState(returnNumber[i]);//代替退货数量
                    orderdetails.add(list.get(listIndex));
                }
            }
        }
        return orderdetails;
    }


    public List<SaExchangInfoVo> saExchangInfozhao(String searchInfo){
        List<SaExchangInfoVo> saExchangInfoVos = orderMapper.saExchangInfozhao(searchInfo);
        return saExchangInfoVos;
    }

    public List<SaRetouerInfoVo> saRouterInfozhao(String selctInfo){
        List<SaRetouerInfoVo> saRetouerInfoVos = orderMapper.saRouterInfozhao(selctInfo);
        return saRetouerInfoVos;

    }


    public List<ZfhuodanEntity>zfhuodanzhao(String selctInfo){
        List<ZfhuodanEntity> zfhuodanzhao = orderMapper.zfhuodanzhao(selctInfo);
        return zfhuodanzhao;


    }
}
